﻿import random
from Game.Poker.DouDiZhu.player import Player
from Game.Poker.Card import Card

class LandlordsGame:
    def __init__(self):
        self.players = [Player("Player1"), Player("Player2"), Player("Player3")]
        self.card = Card()
        self.discards = []  # 当前出牌
        self.current_player = 0
        self.landlord = None

    def deal_cards(self):
        random.shuffle(self.card.deck)
        for i in range(3):
            self.players[i].hand = self.card.deck[i*17 : (i+1)*17]
            self.players[i].sort_hand()
        self.bottom_cards = self.card.deck[-3:]

    def bid_landlord(self):
        # 简化叫地主逻辑
        bids = [random.choice([True, False]) for _ in range(3)]
        for i, bid in enumerate(bids):
            if bid:
                self.landlord = i
                self.players[i].role = 'landlord'
                self.players[i].hand += self.bottom_cards
                self.players[i].sort_hand()
                print(f"{self.players[i].name} becomes landlord!")
                return
        self.landlord = random.randint(0, 2)
        print("Random select landlord")

    def validate_play(self, cards, last_play):
        if not cards:
            return True  # 不出牌

        # 数值映射表（用于顺子比较）
        RANK_VALUES = {'3':3, '4':4, '5':5, '6':6, '7':7, 
                       '8':8, '9':9, '10':10, 'J':11, 'Q':12, 
                       'K':13, 'A':14, '2':15, 'BJ':16, 'RJ':17}
    
        # 预处理卡牌（分离花色）
        card_ranks = []
        for card in cards:
            if card in ['BJ', 'RJ']:
                card_ranks.append(card)
            else:
                rank = card[:-1]  # 去掉花色
                card_ranks.append(rank)

        # 通用验证函数
        def is_sequence(ranks, min_length=5):
            values = []
            for r in ranks:
                if r in ['2', 'BJ', 'RJ']:
                    return False  # 2和王不能加入顺子
                values.append(RANK_VALUES[r])
            values = sorted(list(set(values)))  # 去重并排序
            if len(values) < min_length:
                return False
            # 检查是否连续
            for i in range(1, len(values)):
                if values[i] - values[i-1] != 1:
                    return False
            return True

        # --- 主要验证逻辑 ---
        sorted_ranks = sorted(card_ranks, key=lambda x: RANK_VALUES[x])

        
        if len(card_ranks) == 1:
            return True

        # 王炸（最高优先级）
        if set(card_ranks) == {'BJ', 'RJ'}:
            return True
       

        # 炸弹（四张相同）
        if len(card_ranks) == 4 and len(set(card_ranks)) == 1:
            return True

        # 三带一（3+1）
        if len(card_ranks) == 4:
            # 前三张相同 + 任意一张
            if len(set(sorted_ranks[:3])) == 1:
                return True
            # 任意三张相同 + 单张
            for i in range(2):
                if len(set(sorted_ranks[i:i+3])) == 1:
                    return True
            return False

        # 三带一对（3+2）
        if len(card_ranks) == 5:
            # 前三张相同 + 后两张相同
            if (len(set(sorted_ranks[:3])) == 1 and 
                len(set(sorted_ranks[3:])) == 1):
                return True
            # 中间三张相同 + 两侧对子
            if (len(set(sorted_ranks[1:4])) == 1 and 
                sorted_ranks[0] == sorted_ranks[1] and
                sorted_ranks[3] == sorted_ranks[4]):
                return True
            return False

        # 四带二（4+2单 或 4+2对）
        if len(card_ranks) == 6:
            # 四张相同 + 两张单
            if any(len(set(sorted_ranks[i:i+4])) == 1 for i in range(3)):
                return True
            # 四张相同 + 一对
            if (len(set(sorted_ranks[:4])) == 1 and 
                sorted_ranks[4] == sorted_ranks[5]):
                return True
            return False

        # 四带两对（4+2对）
        if len(card_ranks) == 8:
            # 四张相同 + 两个对子
            if (len(set(sorted_ranks[:4])) == 1 and
                sorted_ranks[4] == sorted_ranks[5] and
                sorted_ranks[6] == sorted_ranks[7]):
                return True
            return False

        # 顺子（5+ 连续单牌）
        if len(card_ranks) >= 5 and is_sequence(card_ranks):
            return True

        # 其他情况（连对、飞机等未实现）
        return False

    def play_round(self):
        while True:
            current = self.players[self.current_player]
            print(f"\n{current.name}'s turn.")
            # 显示带下标的手牌（例如：0:3♠, 1:4♥）
            indexed_hand = [f"{idx}:{card}" for idx, card in enumerate(current.hand)]
            print("Your hand:", ", ".join(indexed_hand))
        
            # 玩家输入下标
            if current.role == 'landlord':
                try:
                    input_str = input("Enter card INDEXES to play (comma separated): ")
                    selected_idxs = [int(idx.strip()) for idx in input_str.split(',') if idx.strip()]
                
                    # 检查下标合法性
                    valid = all(0 <= idx < len(current.hand) for idx in selected_idxs)
                    if not valid:
                        print("Error: Index out of range!")
                        continue
                    if len(selected_idxs) != len(set(selected_idxs)):
                        print("Error: Duplicate indexes!")
                        continue
                
                    # 转换为卡牌
                    play_cards = [current.hand[idx] for idx in selected_idxs]
                except ValueError:
                    print("Error: Invalid input! Please enter numbers.")
                    continue
            else:
                play_cards = []  # 农民AI暂时不出牌

            # 验证出牌规则（原有逻辑）
            if self.validate_play(play_cards, self.discards):
                if play_cards:
                    # 按倒序删除避免索引错位
                    for idx in sorted(selected_idxs, reverse=True):
                        del current.hand[idx]
                    self.discards = play_cards
                    print(f"{current.name} plays: {play_cards}")
                else:
                    print(f"{current.name} passes")
            
                # 检查胜利条件
                if not current.hand:
                    print(f"\n{current.name} wins!")
                    return True
            
                self.current_player = (self.current_player + 1) % 3
                return False
            else:
                print("Invalid play! Try again.")

    def start_game(self):
        print("=== Game Start ===")
        self.deal_cards()
        self.bid_landlord()
        
        # 地主先出牌
        self.current_player = self.landlord
        
        while True:
            game_over = self.play_round()
            if game_over:
                break

if __name__ == "__main__":
    game = LandlordsGame()
    game.start_game()